namespace SharpTalk.Client.WpfApplication.ViewModels
{
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media.Imaging;
    using Converters;
    using Core;
    using Microsoft.Win32;
    using Views;

    public sealed class UserViewModel : ViewModelBase<IUserView>
    {
        private readonly ICommand _createNewCommand = null;
        private readonly ICommand _selectImageCommand = null;
        private readonly ICommand _clearImageCommand = null;

        private User _currentUser = null;
        private readonly ObservableCollection<BitmapImage> _images;
        private bool _imageFolderScanned;

        public UserViewModel(IUserView view) 
            : base(view)
        {
            View.DataContext = this;
            View.SetIcon(Helpers.LoadImage("user_details_16.png"));
            _images = new ObservableCollection<BitmapImage>();
        }

        public UserViewModel(IUserView view, User user)
            : this(view)
        {
            _currentUser = user;
        }

        public ObservableCollection<BitmapImage> Images
        {
            get
            {
                if (!_imageFolderScanned)
                    ScanImageFolder();

                return _images;
            }
        }
        
        public User CurrentUser 
        {
            get
            {
                return _currentUser;
            }
            set
            {
                _currentUser = value; 
                NotifyPropertyChange(()=>CurrentUser);
                NotifyPropertyChange(()=>HasUser);
            }
        }

        public bool HasUser
        {
            get { return CurrentUser != null; }
        }

        public ICommand CreateNewCommand
        {
            get { return _createNewCommand ?? new BindableCommand<object>(OnCreateNew); }
        }
        public ICommand SelectImageCommand
        {
            get { return _selectImageCommand ?? new BindableCommand<object>(OnSelectImage); }
        }
        public ICommand ClearImageCommand
        {
            get { return _clearImageCommand ?? new BindableCommand<object>(OnClearImage); }
        }
        
        private void OnCreateNew(object value)
        {
            if (ShouldTrace(TraceEventType.Verbose)) TraceMethodCall(MethodBase.GetCurrentMethod());
            CurrentUser = new User(){ FirstName = Resources.Messages.label_new };
        }

        private void OnSelectImage(object value)
        {
            if (ShouldTrace(TraceEventType.Verbose)) TraceMethodCall(MethodBase.GetCurrentMethod());
            var ofd = new OpenFileDialog()
                          {
                              CheckFileExists = true,
                              CheckPathExists = true,
                              Filter = "Images|*.png;*.jpg;*.jpeg;*.bmp",
                              FilterIndex = 0,
                              Multiselect = false
                          };

            var result = ofd.ShowDialog((Window) View);
            if (!result.HasValue || !result.Value || string.IsNullOrEmpty(ofd.FileName)) return;
            
            var img = Helpers.LoadImageFromFile(ofd.FileName, 48);
            if(img == null) return;

            try
            {
                File.Copy( ofd.FileName,
                           Path.Combine(@".\\Images\Users", Path.GetFileName(ofd.FileName)));
            }
            catch 
            {
            }

            var conv = new BinaryToBitmapImageConverter();
            CurrentUser.Image = conv.ConvertBack(img, typeof (byte[]), null, CultureInfo.CurrentUICulture) as byte[];
        }

        private void OnClearImage(object value)
        {
            if (ShouldTrace(TraceEventType.Verbose)) TraceMethodCall(MethodBase.GetCurrentMethod());
            CurrentUser.Image = null;
        }

        private void ScanImageFolder()
        {
            if (ShouldTrace(TraceEventType.Verbose)) TraceMethodCall(MethodBase.GetCurrentMethod());
            foreach (var img in
                Directory.EnumerateFiles(@".\\Images\Users", "*.*", SearchOption.TopDirectoryOnly).Select(file => Helpers.LoadImageFromFile(file, 48)))
            {
                if(img!=null)
                    _images.Add(img);
            }

            _imageFolderScanned = true;
        }
    }
}